package com.atguigu.springcloud.controller;

import com.atguigu.springcloud.entities.Payment;
import com.atguigu.springcloud.result.CommonResult;
import com.atguigu.springcloud.service.PaymentService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.List;
import java.util.concurrent.TimeUnit;

/**
 * @author yanglin
 * @create 2023-11-08 16:36 星期三
 * description:
 */
@RestController
@Slf4j
public class PaymentController {
    
    @Resource
    private PaymentService paymentService;
    
    @Value("${server.port}")
    private String serverPort;
    
    @Resource
    private DiscoveryClient discoveryClient;
    
    @PostMapping("/payment/create")
    public CommonResult create(@RequestBody Payment payment){
        int add = paymentService.add(payment);
        log.info("插入结果：{}",add);
        if (add > 0 ){
            return new CommonResult(200,"插入数据库成功,端口号：" + serverPort,add);
        }else {
            return new CommonResult(444,"插入数据库失败,端口号：" + serverPort);
        }
    }
    
    @GetMapping("/payment/get/{id}")
    public CommonResult getPaymentById(@PathVariable("id") Long id){
        Payment payment = paymentService.getPaymentById(id);
        if (payment != null){
            return new CommonResult(200,"查询成功,端口号：" + serverPort,payment);
        }else {
            return new CommonResult(201,"查询失败,没有id为 " + id + "的记录,端口号：" + serverPort,null);
        }
    }
    
    
    @GetMapping("/payment/discovery")
    public Object discovery(){
        List<String> services = discoveryClient.getServices();
        for (String service : services) {
            log.info("******element:" + service);
        }

        List<ServiceInstance> instances = discoveryClient.getInstances("CLOUD-PAYMENT-SERVICE");
        for (ServiceInstance instance : instances) {
            log.info(instance.getServiceId() + "\t" + instance.getHost() + "\t" + instance.getUri() + "\t" + instance.getPort());
        }
        
        return this.discoveryClient;
    }


    /**
     * 测试自定义负载均衡算法
     * @return
     */
    @GetMapping("/payment/lb")
    public String getPaymentLB(){
        return serverPort;    
    }
    
    
    @GetMapping("/payment/feign/timeout")
    public String paymentFeignTimeOut(){
        try {
            Thread.sleep(3000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        
        return serverPort;
    }
    
    // ----测试zipkin----
    
    @GetMapping("/payment/zipkin")
    public String paymentZipkin(){
        return "hi, I am payment zipkin server fall back, welcome to atguigu";
    }
    
}
